#include <iostream>

// 模板类: 模板化的是成员变量的类型
// 类模板的名字不能单独作为类型出现
// 得根模板的类型参数一起
// 类模板的定义： 必须是显式调用

// 类模板的声明和定义不能分开
template <typename T>
class DynamicArray
{
public:
    DynamicArray();
    ~DynamicArray();
    DynamicArray(const DynamicArray &Array);

    DynamicArray operator=(const DynamicArray &Array);

    void InserTail(const T &element);

    void RemoveByIndex(int index);

    void show();

    //友元不能共享类模板的模板声明，而且不能重名
    template <typename T1>
    friend std::ostream& operator<<(std::ostream &os, const DynamicArray<T1> &Array);

private:
    T *a;
    int size;
    int capacity;
};

// 函数是类外定义,上面的声明只作用于类定义
template <typename T>
DynamicArray<T>::DynamicArray()
{
    // std::cout<<"无参构造"<<std::endl;
    capacity = 15;
    size = 0;
    a = new T[capacity];
}

template <typename T>
DynamicArray<T>::~DynamicArray()
{
    // std::cout<<"析构函数"<<std::endl;
    delete[] a;
}

template <typename T>
DynamicArray<T>::DynamicArray(const DynamicArray<T> &Array)
{
    // std::cout<<"拷贝构造"<<std::endl;
    capacity = Array.capacity;
    size = Array.size;
    a = new T[capacity];
    for (int i = 0; i < size; i++)
    {
        a[i] = Array.a[i];
    }
}

template <typename T>
DynamicArray<T> DynamicArray<T>::operator=(const DynamicArray<T> &Array)
{
    // std::cout<<"赋值重载"<<std::endl;
    delete[] a;
    capacity = Array.capacity;
    size = Array.size;
    a = new T[capacity];
    for (int i = 0; i < size; i++)
    {
        a[i] = Array.a[i];
    }
    return *this;
}

template <typename T>
void DynamicArray<T>::InserTail(const T &element)
{
    // std::cout<<"尾部添加"<<std::endl;
    if (size >= capacity)
    {
        capacity *= 2;
        T *newP = new T[capacity];
        for (int i = 0; i < size; i++)
        {
            newP[i] = a[i];
        }
        delete[] a;
        a = newP;
    }
    a[size++] = element;
}

template <class T>
void DynamicArray<T>::show()
{
    for (int i = 0; i < size; i++)
    {
        std::cout << a[i] << std::endl;
    }
}

template <class T>
void DynamicArray<T>::RemoveByIndex(int index)
{
    if (index < 0 || index >= size)
    {
        std::cout << "不合法的数" << std::endl;
        return;
    }
    for (int i = index; i < size - 1; i++)
    {
        a[i] = a[i + 1];
    }
    size--;
}

template<typename T>
std::ostream& operator<<(std::ostream &os, const DynamicArray<T> &Array)
{
    for(int i=0; i<Array.size; i++)
    {
        os<<Array.a[i]<<" ";
    }
    return os;
}